import {HtmlNodeOptions, IContext} from "./interfaces";
import {collectJsxEvents, disposeJsxEvents} from "@/utils/jsx-runtime.ts";

export class HtmlNode {
  $ctx: IContext | undefined
  $el = null as unknown as HTMLElement
  readonly tag: string
  protected _elEvents: any

  constructor(options: HtmlNodeOptions = {}) {
    const {tag = 'div', autoSetupEl = true} = options
    this.tag = tag

    if (autoSetupEl) {
      this.$setupEl()
    }
  }

  $setupEl() {
    this.disposeEvents()
    const {htmlElement, events} = collectJsxEvents(()=>this._createEl())
    this.$el = htmlElement
    this._elEvents = events
  }

  protected _createEl() {
    return document.createElement(this.tag)
  }

  mount(el: HTMLElement) {
    el.appendChild(this.$el)
  }

  disposeEvents() {
    if (this._elEvents) {
      disposeJsxEvents(this._elEvents)
      this._elEvents = null
    }
  }
}